package com.blb.day14_bookms.controller;


import com.blb.day14_bookms.entity.Book;
import com.blb.day14_bookms.entity.JsonResult;
import com.blb.day14_bookms.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chenheng
 * @since 2020-08-06
 */
@CrossOrigin
@RestController  //RestController = Controller + ResponseBody
@RequestMapping("/book")
public class BookController {

    @Autowired
    private IBookService bookService;

    @RequestMapping("/findAll")
    public JsonResult findAll(){
        try {
            List<Book> books = bookService.list();
            return new JsonResult(1,books);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(0,null);
        }
    }

    @PostMapping("/saveBook")
    public JsonResult saveBook(@RequestBody Book book){
        try {
            //添加或更新，id为空就是添加，不为空就是更新
            bookService.saveOrUpdate(book);
            return new JsonResult(1, null);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(0,null);
        }
    }

    @PostMapping("/deleteBook")
    public JsonResult deleteBook(@RequestBody Book book){
        try {
            bookService.removeById(book.getId());
            return new JsonResult(1, null);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(0,null);
        }
    }
}

